/*
 * ============================================================================
 *
 *       Filename:  http.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  01/26/2018 05:39:55 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *   Organization:  
 *
 * ============================================================================
 */
#include <stdio.h>
#include <stdint.h>
#include <curl/curl.h>

#include "http.h"
#include "arg.h"

size_t just_return( char *ptr, size_t size, size_t  nmemb,  void *userdata)
{
	return size * nmemb;
}

int  http_send(char *url, char *data, void *callback, struct curl_slist * headers)
{
	int retval = 0;
	if(callback == NULL)
		callback = just_return;

	CURL *handle;
	handle = curl_easy_init();
	if(handle == NULL) {
		sys_err("Init curl failed:%m\n");
		exit(-1);
	}

	CURLcode ret;

	if(args_info.curldebug_flag) {
		/* set verbose */
		ret = curl_easy_setopt(handle, CURLOPT_VERBOSE, 1);
		if(ret != CURLE_OK) {
			sys_err("set verbose option failed:%m\n");
			exit(-1);
		}
		sys_debug("curl send: \nurl:%s\ndata:%s\n", url, data);
	}

	/* http headers */
	if(headers) {
		ret = curl_easy_setopt(handle, CURLOPT_HTTPHEADER, headers);
		if(ret != CURLE_OK) {
			sys_err("set httpheader option failed:%m\n");
			exit(-1);
		}
	}
	/* set post data */
	if(data) {
		/* set post */
		ret = curl_easy_setopt(handle, CURLOPT_POST, 1);
		if(ret != CURLE_OK) {
			sys_err("set post option failed:%m\n");
			exit(-1);
		}

		ret = curl_easy_setopt(handle, CURLOPT_POSTFIELDS, data);
		if(ret != CURLE_OK) {
			sys_err("set post data option failed:%m\n");
			exit(-1);
		}
	}

	if(callback != NULL) {
		/* set ret_call */
		ret = curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, callback);
		if(ret != CURLE_OK) {
			sys_err("set post data option failed:%m\n");
			exit(-1);
		}
	}

	ret = curl_easy_setopt(handle, CURLOPT_TIMEOUT, 
		args_info.httptimeout_arg);
	if(ret != CURLE_OK) {
		sys_err("set timeout option failed:%m\n");
		exit(-1);
	}

	ret = curl_easy_setopt(handle, CURLOPT_URL, url);
	if(ret != CURLE_OK) {
		sys_err("set url option failed:%m\n");
		exit(-1);
	}

	ret = curl_easy_perform(handle);
	if(ret != CURLE_OK) {
		sys_err("curl perform failed:%s\n", url);
		retval = -1;
		goto end;
	}
	sys_debug("curl perform success:%s\n", url);

end:
	curl_easy_cleanup(handle);
	if(headers)
		curl_slist_free_all(headers);
	return retval;
}
